package com.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("msg","Hello shiro!");
        return "index";
    }
    @RequestMapping("/user/add")
    public String toadd(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String toupdate(){
        return "user/update";
    }

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装前端的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);//此方法是核心方法！会进入自定义Realm类中
            /*Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("loginUser",subject);*/
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在!");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不正确");
            return "login";
        }
    }
    @RequestMapping("/noperms")
    @ResponseBody
    public String nopperms(){
        return "未经授权的访问操作！";
    }
    @RequestMapping("/logout")
    public String loginout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
